<template>
	<view>
		<!-- 头像 -->
		<view class="wrap_nb cflex">
			<view class="dflex jcsb aic pb12">
				<view class="fg1 cflex">
					<text class="f14">头像</text>
					<text class="f12 ca3a3a3">建议尺寸500*500px</text>
				</view>

				<!-- #ifdef MP-WEIXIN -->
				<view class="dflex aic">
					<lxiaoxiao-cropper selWidth="300" selHeight="300" :avatarSrc="avatarSrc"
						avatarStyle="width:40px; height:40px; border-radius:40px;" @upload="avatarUpload">
					</lxiaoxiao-cropper>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
				<!-- #endif -->

				<!-- #ifdef MP-TOUTIAO -->
				<view class="dflex aic" @click="UploadForTouTiao">
					<u-avatar :src="avatarSrc" size="40"></u-avatar>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
				<!-- #endif -->

			</view>
			<u-line></u-line>
		</view>

		<!-- 背景图 -->
		<view class="wrap_nb cflex">
			<view class="dflex jcsb aic pb12">
				<view class="fg1 cflex">
					<text class="f14">背景图</text>
					<text class="f12 ca3a3a3">建议尺寸1080*457px</text>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<view class="profile_background dflex aic">
					<lxiaoxiao-cropper selWidth="300" selHeight="127" :avatarSrc="bannerSrc"
						avatarStyle="width:75px; height:40px;" @upload="bannerUpload"></lxiaoxiao-cropper>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
				<!-- #endif -->

				<!-- #ifdef MP-TOUTIAO -->
				<view class="profile_background dflex aic" @click="UploadForTouTiao">
					<image :src="bannerSrc" mode="widthFix" style="height: 30px; width: 75px; "></image>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
				<!-- #endif -->
			</view>
			<u-line></u-line>
		</view>

		<!-- 昵称 -->
		<view class="wrap_nb cflex" @click="openEditUserName">
			<view class="profile_list dflex jcsb aic pb12">
				<view class="fg1">
					<text class="f14">昵称</text>
				</view>
				<view class="profile_background dflex aic">
					<text class="f14">{{ userNameValue }}</text>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			<u-line></u-line>
		</view>

		<!-- 性别 -->
		<view class="wrap_nb cflex" @click="openEditUserSex">
			<view class="profile_list dflex jcsb aic pb12">
				<view class="fg1">
					<text class="f14">性别</text>
				</view>
				<view class="profile_background dflex aic">
					<text class="f14">{{ userSexValue }}</text>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			<u-line></u-line>
		</view>

		<!-- 生日 -->
		<view class="wrap_nb cflex" @click="openEditBirthday">
			<view class="profile_list dflex jcsb aic pb12">
				<view class="fg1">
					<text class="f14">生日</text>
				</view>
				<view class="profile_background dflex aic">
					<text class="f14">{{ birthdayFormat(userBirthdayValue) }}</text>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			<u-line></u-line>
		</view>

		<!-- 简介 -->
		<view class="wrap_nb cflex" @click="openEditIntro">
			<view class="profile_list dflex jcsb aic pb12">
				<view class="fg1">
					<text class="f14">简介</text>
				</view>
				<view class="profile_background dflex aic">
					<text class="f14 u-line-1">{{ userIntroValue }}</text>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			<u-line></u-line>
		</view>

		<!-- 行业 -->
		<view class="wrap_nb cflex" @click="openEditUserJob">
			<view class="profile_list dflex jcsb aic pb12">
				<view class="fg1">
					<text class="f14">行业</text>
				</view>
				<view class="profile_background dflex aic">
					<text class="f14">{{ userJobValue }}</text>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			<u-line></u-line>
		</view>

		<!-- 职位 -->
		<view class="wrap_nb cflex" @click="openEditUserOcc">
			<view class="profile_list dflex jcsb aic pb12">
				<view class="fg1">
					<text class="f14">职位</text>
				</view>
				<view class="profile_background dflex aic">
					<text class="f14">{{ userOccValue }}</text>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			<u-line></u-line>
		</view>

		<view class="wrap mt12">
			<u-button color="#FFD84A" shape="circle" throttleTime="2000" @click="updateUserInfo">
				<text style="color: #000;">保存资料</text>
			</u-button>
		</view>

		<view class="wrap" style="padding: 0 12px">
			<u-button color="#eee" shape="circle" throttleTime="2000" @click="exitLogin">
				<text style="color: #000;">退出登录</text>
			</u-button>
		</view>

		<version></version>

		<!-- 编辑昵称 -->
		<u-popup :show="showEditUserName" @close="closeEditUserName" mode="top" :safeAreaInsetBottom="false">
			<view class="wrap">
				<view class="pop_header dflex jcc">
					<text class="f18 fbold">编辑昵称</text>
				</view>
				<view class="mt12">
					<u--form labelPosition="left" :model="editUserNameModel" ref="editUserNameForm">
						<u-form-item prop="editUser.name" ref="item1">
							<u--input v-model="editUserNameModel.editUser.name" border="surround" placeholder="请输入您的昵称"
								confirmType="send" prefixIcon="account" shape="circle" type="text" ref="popInput">
							</u--input>
						</u-form-item>
					</u--form>
				</view>
				<view class="pop_header dflex jcsb aic mt20">
					<text class="f14" @click="cancelEditUserName">取消</text>
					<!-- #ifdef MP-TOUTIAO -->
					<text class="f14" @click="confirmEditUserNameForTouTiao">保存</text>
					<!-- #endif -->
					<!-- #ifdef MP-WEIXIN -->
					<text class="f14" @click="confirmEditUserName">保存</text>
					<!-- #endif -->
				</view>
			</view>
		</u-popup>

		<!-- 编辑性别 -->
		<u-picker :show="showEditUserSex" :columns="sexColumns" :defaultIndex="[sexDefault]" @close="closeEditUserSex"
			closeOnClickOverlay="true" @confirm="confirmEditUserSex" @change="changeEditUserSex"
			@cancel="cancelEditUserSex" title="编辑性别">
		</u-picker>

		<!-- 编辑生日 -->
		<u-datetime-picker :show="showEditBirthday" :v-model="userBirthdayValue" minDate="0" title="编辑生日"
			closeOnClickOverlay="true" @close="closeEditBirthday" @confirm="confirmEditBirthday"
			@change="changeEditBirthday" @cancel="cancelEditBirthday" mode="date"></u-datetime-picker>

		<!-- 编辑简介 -->
		<u-popup :show="showEditUserIntro" @close="closeEditUserIntro" mode="top" :safeAreaInsetBottom="false">
			<view class="wrap">
				<view class="pop_header dflex jcc">
					<text class="f18 fbold">编辑简介</text>
				</view>
				<u--form labelPosition="left" :model="editUserNameModel" ref="userForm">
					<u-form-item prop="editUser.intro" ref="item1">
						<u-textarea height='150' @input="inputEditUserIntro" v-model="editUserNameModel.editUser.intro"
							placeholder="请输入内容" maxlength="200" count="true"></u-textarea>
					</u-form-item>
				</u--form>
				<text style="margin: 5px 10px 0 0; color: #999;" class="dflex f14">更详细的说明自己，会增加他人对你的信任的关注哦</text>
				<view class="pop_header dflex jcsb aic mt20">
					<text class="f14" @click="closeEditUserIntro">取消</text>
					<text class="f14" @click="confirmEditUserIntro">保存</text>
				</view>
			</view>
		</u-popup>

		<!-- 编辑行业 -->
		<u-picker :show="showEditUserJob" :columns="jobColumns" :defaultIndex="[jobDefault]" @close="closeEditUserJob"
			closeOnClickOverlay="true" @confirm="confirmEditUserJob" @change="changeEditUserJob"
			@cancel="cancelEditUserJob" keyName="name" title="编辑行业">
		</u-picker>

		<!-- 编辑职业 -->
		<u-picker :show="showEditUserOcc" :columns="occColumns" :defaultIndex="[occDefault]" @close="closeEditUserOcc"
			closeOnClickOverlay="true" @confirm="confirmEditUserOcc" @change="changeEditUserOcc"
			@cancel="cancelEditUserOcc" keyName="name" title="编辑职业">
		</u-picker>

		<u-modal :show="exitModal" title="退出确认" content="确认要退出当前账号登录吗？" showCancelButton="true" @confirm="ensureExit"
			@cancel="closeExit" @close="closeExit">
		</u-modal>

		<u-toast ref="uToast"></u-toast>

	</view>
</template>

<script>
	// 昵称不能重复前端判断 ？ 可以
	// 生日默认数据加载

	

	export default {
		data() {
			return {
				bannerSrc: "",
				avatarSrc: '',
				showEditUserName: false,
				showEditUserSex: false,
				showEditBirthday: false,
				showEditUserIntro: false,
				showEditUserJob: false,
				showEditUserOcc: false,
				sexColumns: [
					['女', '男']
				],
				jobColumns: [],
				occColumns: [],
				editUserNameModel: {
					editUser: {
						name: '',
						intro: ''
					}
				},
				userNameValue: '',
				userSexValue: '',
				userBirthdayValue: ``,
				userIntroValue: '',
				userJobValue: '',
				userOccValue: '',
				userJobSqlValue: '',
				userOccSqlValue: '',
				userSexSqlValue: '',
				jobDefault: '',
				occDefault: '',
				sexDefault: '',
				rules: {
					// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
					'editUser.name': [{
						type: 'string',
						required: true,
						message: '昵称不能为空',
						trigger: ['change', 'blur']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.rangeLength(value, [1, 20]);
						},
						trigger: ["change", "blur"],
						message: '昵称字数请介于1-20之间',
					}],
				},
				avatarList1: [],
				bannerList1: [],
				exitModal: false
			}
		},
		onReady() {
			// #ifdef MP-WEIXIN
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.editUserNameForm.setRules(this.rules)
			// #endif 
		},
		onLoad: function() {
			// console.log(uni.$u.page());
			uni.showLoading({
				title: '加载中...'
			})
			uni.request({
				url: uni.getStorageSync('domain') + '/api/v1/user_profile',
				method: 'get',
				header: {
					'Accept': 'application/json',
					'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info').access_token
				},
				success: (res) => {
					if (res.statusCode == 401) {
						// console.log('res', res.statusCode);
						uni.removeStorageSync('access_member_info');
						uni.navigateTo({
							url: '/pages/register/register'
						})
					}
					if (res.statusCode == 200) {
						// console.log('res', res.data);
						this.editUserNameModel.editUser.name = res.data.name
						this.userNameValue = res.data.name
						this.editUserNameModel.editUser.intro = res.data.intro
						this.userIntroValue = res.data.intro
						this.userBirthdayValue = res.data.birthday
						this.userSexValue = res.data.sex == 0 ? '女' : '男'
						this.userSexSqlValue = res.data.sex
						this.userJobValue = res.data.job_id.name
						this.userJobSqlValue = res.data.job_id.id
						this.userOccValue = res.data.occ_id.name
						this.userOccSqlValue = res.data.occ_id.id
						//列表默认值，后台排序一定要是从小到大连贯的数字
						this.jobDefault = res.data.job_id.sort - 1
						this.occDefault = res.data.occ_id.sort - 1
						this.sexDefault = res.data.sex
						this.avatarSrc = res.data.avatar + '?' + uni.$u.random(1, 9999)
						this.bannerSrc = res.data.banner + '?' + uni.$u.random(1, 9999)
						// console.log('res', this.userJobSqlValue);
						uni.hideLoading();
					}
				},
				fail: (res) => {}
			})
		},
		methods: {
			avatarUpload(rsp) {
				const self = this;
				// rsp.avatar.imgSrc = rsp.path; //更新头像方式二
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.getStorageSync('domain') + '/api/v1/user/profile_img',
						filePath: rsp.path,
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info')
								.access_token,
						},
						name: 'img',
						formData: {
							'type': 'user_avatar',
							'width': 500
						},
						success: (res) => {
							// console.log(src);
							var src = JSON.parse(res.data).images;
							self.avatarSrc = src + '?' + uni.$u.random(1, 9999)
							// this.avatarSrc = src + '?' + uni.$u.random(1, 9999)
						},
						fail: (err) => {
							console.log(err);
						}
					});
				})
			},
			UploadForTouTiao() {
				this.show_toast('小程序端暂不支持更换头像')
			},
			bannerUpload(rsp) {
				const self = this;
				// rsp.avatar.imgSrc = rsp.path; //更新头像方式二
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.getStorageSync('domain') + '/api/v1/user/profile_img',
						filePath: rsp.path,
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info')
								.access_token,
						},
						name: 'img',
						formData: {
							'type': 'user_banner',
							'width': 1080
						},
						success: (res) => {
							// console.log(src);
							var src = JSON.parse(res.data).images;
							self.bannerSrc = src + '?' + uni.$u.random(1, 9999)
							// this.avatarSrc = src + '?' + uni.$u.random(1, 9999)
						},
						fail: (err) => {
							console.log(err);
						}
					});
				})
			},
			show_toast(mes) {
				this.$refs.uToast.show({
					message: mes,
				})
			},
			//编辑昵称
			openEditUserName() {
				this.showEditUserName = true
			},
			closeEditUserName() {
				this.showEditUserName = false
			},
			confirmEditUserName() {
				this.$refs.editUserNameForm.validate().then(res => {
					this.userNameValue = this.editUserNameModel.editUser.name;
					this.showEditUserName = false;
				}).catch(errors => {
					console.log(errors);
					this.show_toast('昵称填写请符合规范')
				})
			},
			confirmEditUserNameForTouTiao() {
				this.userNameValue = this.editUserNameModel.editUser.name;
				this.showEditUserName = false;
			},
			cancelEditUserName() {
				this.showEditUserName = false
			},
			//编辑性别
			openEditUserSex() {
				this.editUserNameModel.editUser.name = this.userNameValue
				this.showEditUserSex = true
			},
			closeEditUserSex() {
				this.showEditUserSex = false
			},
			confirmEditUserSex(e) {
				this.userSexValue = e.value[0];
				this.showEditUserSex = false
				this.userSexSqlValue = e.value[0] == '女' ? 0 : 1
				// console.log(e.value[0])
				// console.log(this.userSexSqlValue)
			},
			changeEditUserSex(e) {
				// console.log(e.value[0])
			},
			cancelEditUserSex() {
				this.showEditUserSex = false
			},
			//编辑生日
			openEditBirthday() {
				this.userBirthdayValue = parseInt(this.userBirthdayValue)
				this.showEditBirthday = true
				console.log(this.userBirthdayValue)
			},
			closeEditBirthday() {
				this.showEditBirthday = false
			},
			confirmEditBirthday(e) {
				console.log(e.value)
				this.userBirthdayValue = e.value
				this.showEditBirthday = false
			},
			changeEditBirthday(e) {
				console.log(e.value)
			},
			cancelEditBirthday() {
				this.showEditBirthday = false
			},
			birthdayFormat(val) {
				var y = new Date(val).getFullYear();
				var m = (new Date(val).getMonth() + 1 < 10) ? '0' + (new Date(val).getMonth() + 1) : (new Date(val)
					.getMonth() + 1);
				var d = (new Date(val).getDate() < 10) ? '0' + new Date(val).getDate() : new Date(val).getDate();
				return y + '-' + m + '-' + d
			},
			// 编辑简介
			openEditIntro() {
				this.showEditUserIntro = true
			},
			closeEditUserIntro() {
				this.showEditUserIntro = false
			},
			confirmEditUserIntro() {
				// console.log(this.editUserNameModel.editUser.intro)
				this.userIntroValue = this.editUserNameModel.editUser.intro
				this.showEditUserIntro = false
			},
			inputEditUserIntro(e) {
				this.editUserNameModel.editUser.intro = e
				// console.log(e)
			},
			cancelEditUserIntro() {
				this.showEditUserIntro = false
			},
			//编辑行业
			openEditUserJob() {
				uni.showLoading({
					title: '加载中...',

				});
				uni.request({
					url: uni.getStorageSync('domain') + '/api/v1/user/jobs_list',
					method: 'GET',
					header: {
						'Accept': 'application/json',
					},
					success: (res) => {
						this.jobColumns = [res.data]
						this.showEditUserJob = true
						uni.hideLoading();
					}
				})
			},
			closeEditUserJob() {
				this.showEditUserJob = false
			},
			confirmEditUserJob(e) {
				this.userJobValue = e.value[0].name
				this.userJobSqlValue = e.value[0].id
				console.log(e.value[0].name, e.value[0].id)
				this.showEditUserJob = false
			},
			changeEditUserJob(e) {
				console.log(e.value[0].name, e.value[0].id)
			},
			cancelEditUserJob() {
				this.showEditUserJob = false
			},
			//编辑职位
			openEditUserOcc() {
				uni.showLoading({
					title: '加载中...',

				});
				uni.request({
					url: uni.getStorageSync('domain') + '/api/v1/user/occs_list',
					method: 'GET',
					header: {
						'Accept': 'application/json',
					},
					success: (res) => {
						this.occColumns = [res.data]
						this.showEditUserOcc = true
						uni.hideLoading();
					}
				})
			},
			closeEditUserOcc() {
				this.showEditUserOcc = false
			},
			confirmEditUserOcc(e) {
				this.userOccValue = e.value[0].name
				this.userOccSqlValue = e.value[0].id
				this.showEditUserOcc = false
			},
			changeEditUserOcc(e) {
				// console.log(e.value)
			},
			cancelEditUserOcc() {
				this.showEditUserOcc = false
			},
			//保存资料
			updateUserInfo() {
				uni.showLoading({
					title: '保存中...'
				})
				uni.request({
					url: uni.getStorageSync('domain') + '/api/v1/user',
					method: "PATCH",
					header: {
						'Accept': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					data: {
						'name': this.userNameValue,
						//由于要避免缓存造成的用户头像上传后显示不及时，加了问好和4位随机数
						//保存的时候要删除，前端需要及时更新的地方再加上
						//保存到数据库容易造成多次重复增加
						'avatar': this.avatarSrc.substring(0, this.avatarSrc.indexOf('?')),
						'banner': this.bannerSrc.substring(0, this.bannerSrc.indexOf('?')),
						'sex': this.userSexSqlValue,
						'birthday': this.userBirthdayValue,
						'intro': this.editUserNameModel.editUser.intro,
						'job_id': this.userJobSqlValue,
						'occ_id': this.userOccSqlValue
					},
					success: (res) => {
						console.log(res)
						if (res.statusCode != 201) {
							// console.log(res);
							this.show_toast(res.data.message)
						} else {
							if (res.data.status == 'success') {
								//判断用户是否提交了修改
								this.show_toast('保存成功')
								setTimeout(function() {
									uni.reLaunch({
										url: '/pages/member/member',
									})
								}, 1500)
							}
							if (res.data.status == 'fail') {
								this.show_toast('保存失败')
							}
						}
						uni.hideLoading()
					},
					fail: (res) => {
						console.log(res)
					}
				})
			},
			exitLogin() {
				this.exitModal = true
			},
			ensureExit() {
				console.log('退出流程')
				uni.showLoading({
					title: '退出中...',
					duration: 10000,
					mask: true
				});
				uni.request({
					url: uni.getStorageSync('domain') + '/api/v1/user/currentToken',
					method: 'DELETE',
					header: {
						'Accept': 'application/json',
						'Authorization': 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {
						if (res.statusCode == 204) {
							uni.removeStorageSync('access_member_info')
							//销毁用户登录类型，因为用手机登录和微信登录走的发布流程不一致
							uni.removeStorageSync("login_type")
							this.show_toast('退出成功')
							setTimeout(function() {
								uni.navigateTo({
									url: '/pages/index/index'
								})
							}, 1500);
						}
					}
				})
			},
			closeExit() {
				this.exitModal = false
			}

		}
	}
</script>

<style>
	.profile_background image {
		width: 75px;
		height: 40px;
		border-radius: 5px;
	}

	.profile_list {
		height: 40px;
	}

	.safe_buttom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		padding-bottom: 35px;
		box-sizing: border-box;
	}
</style>
